package cn.wit.summit.chwan.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.ImageCollectionAdapter;
import cn.wit.summit.chwan.interfaces.MyScrollListener;
import cn.wit.summit.chwan.models.response.ImageListByTypeResponse;
import cn.wit.summit.chwan.models.response.PicCollectionTypeListResponse;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.activity.ImagePagerV2Activity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.widgets.SpacesItemDecoration;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/7/14.
 */

public class ImageCollectionFragment extends BaseFragment implements ImageCollectionAdapter.OnClickItemListener {

    @Bind(R.id.imageListFragmentRv)
    RecyclerView imageListFragmentRv;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private PicCollectionTypeListResponse.PicListBean typeBean;
    private String gameId;
    private int page;
    private int pn = 1;
    private int pc = 10;
    private GridLayoutManager manager;
    private ImageCollectionAdapter adapter;
    private List<ImageCollectionAdapter.ViewBean> datas = new ArrayList<>();
    private List<ImageListByTypeResponse.PicListBean> readData = new ArrayList<>();

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    public static ImageCollectionFragment newInstance(PicCollectionTypeListResponse.PicListBean data, String gameId, int page) {
        Bundle args = new Bundle();
        args.putString("gameId", gameId);
        args.putInt("page", page);
        args.putSerializable("typeBean", data);
        ImageCollectionFragment fragment = new ImageCollectionFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_image_collection, null);
        ButterKnife.bind(this, view);

        typeBean = (PicCollectionTypeListResponse.PicListBean) getArguments().getSerializable("typeBean");
        gameId = getArguments().getString("gameId");
        page = getArguments().getInt("page");
        LogUtils.e("tbl:"+typeBean.getTitle());

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        manager = new GridLayoutManager(getActivity(),2);
        adapter = new ImageCollectionAdapter(getActivity(), datas, this);
        imageListFragmentRv.setLayoutManager(manager);
        imageListFragmentRv.addItemDecoration(new SpacesItemDecoration(27, 32));
        imageListFragmentRv.setAdapter(adapter);
        imageListFragmentRv.setFocusable(false);
        imageListFragmentRv.addOnScrollListener(new MyScrollListener());
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                pn = 1;
                getWebData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                getWebData();
            }
        });

        return view;
    }

    private void getWebData() {
        if (typeBean!=null) {
            api.getPicList(gameId, typeBean.getId(), pn, pc).enqueue(new MyCallback<ResponseBase<ImageListByTypeResponse>>() {
                @Override
                public void onSuccess(ResponseBase<ImageListByTypeResponse> model) {
                    ImageListByTypeResponse data = model.getData_info();
                    setDataToView(data);
                }

                @Override
                public void onFailure(int code, String msg) {
                    if (refreshLayout!=null) {
                        refreshLayout.finishRefresh(false);
                        refreshLayout.finishLoadMore(false);
                        refreshLayout.finishRefresh();
                    }
                    showToast(msg);
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity()!=null && pn==1) {
            if (getUserVisibleHint()) {
                getWebData();
            } else {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getWebData();
                    }
                }, 300 * page);
            }
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getActivity()!=null && isVisibleToUser && pn==1) {
            getWebData();
        }
    }

    private void setDataToView(ImageListByTypeResponse data) {
        if (data==null || data.getPicList()==null || data.getPicList().size()==0) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                if (refreshLayout!=null){
                    refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                }
            }
            return;
        }

        if (pn == 1) {
            readData.clear();
            adapter.clearData();
            datas.clear();
        }

        readData.addAll(data.getPicList());

        for (int i = 0; i < data.getPicList().size(); i++) {
            datas.add(new ImageCollectionAdapter.ViewBean(ImageCollectionAdapter.ViewType.TYPE_BASE, data.getPicList().get(i)));
        }

        if (refreshLayout!=null) {
            if (data==null || data.getPicList().size() <= 0) {
                if (pn == 1) {
                    refreshLayout.finishRefresh();
                } else {
                    refreshLayout.finishLoadMore();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
//                        refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                        }
                    }, 200);
                }
            } else {
                if (pn == 1) {
                    refreshLayout.finishRefresh();
                } else {
                    refreshLayout.finishLoadMore();
                }
                pn++;
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onClick(int position) {
        try {
            Intent intent = new Intent(getContext(), ImagePagerV2Activity.class);
            Bundle bundle=new Bundle();
            bundle.putSerializable(ImagePagerV2Activity.EXTRA_IMAGE_DATA,(Serializable)readData);
            intent.putExtras(bundle);
            intent.putExtra(ImagePagerV2Activity.EXTRA_IMAGE_INDEX, position);
            intent.putExtra(ImagePagerV2Activity.EXTRA_TOTAL, typeBean.getPicCount());
            intent.putExtra(ImagePagerV2Activity.EXTRA_PN, pn);
            intent.putExtra(ImagePagerV2Activity.EXTRA_PC, pc);
            intent.putExtra(ImagePagerV2Activity.EXTRA_ID, typeBean.getId());
            intent.putExtra(ImagePagerV2Activity.EXTRA_GAMEID, gameId);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
